/**
 * 
 */
package cc.rico.sync;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;

import cc.rico.api.BaseZK;
import cc.rico.utils.ZkUtil;

/**
 * @author rico 2016年8月20日
 *
 */
public class ZkReceiver extends BaseZK implements Watcher {
	private static final String SYNC_PATH = "/sync";
	private ZooKeeper zk = null;
	private String host;
	
	public ZkReceiver(String host) {
		this.host = host;
		zk = ZkUtil.getInstance(host, this);
		
		String data = getData();
		logger.info("data = {}", data);
	}
	
	/**
	 * 读取sync数据
	 * @return
	 */
	public String getData() {
		String data = null;
		try {
			//if(zk.exists(SYNC_PATH, null) != null) {
				data = new String(zk.getData(SYNC_PATH, this, null));
			//}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		return data;
	}
	
	public void close() {
		ZkUtil.close(zk);
	}
	
	@Override
	public void process(WatchedEvent event) {
		logger.info("state={}, type={}", event.getState(), event.getType());
		
		if(event.getType() == EventType.NodeDataChanged) {
			logger.info("host={}, data={}", this.host, this.getData());
		}
	}
	
}
